package org.tinygroup.dbrouterjdbc3.sqlprocessor.pagedata;

import org.tinygroup.jsqlparser.extend.ParameterFinder.ParameterEntry;
import org.tinygroup.jsqlparser.statement.select.Limit;
import org.tinygroup.jsqlparser.statement.select.PlainSelect;
import org.tinygroup.jsqlparser.statement.select.Select;
import org.tinygroup.jsqlparser.statement.select.SelectBody;

/**
 * limit子句格式的分页处理
 * @author renhui
 *
 */
public class LimitPageDataProcess implements PageDataProcess {
	
	private ThreadLocal<Limit> threadLocal=new ThreadLocal<Limit>();

	public boolean isMatch(Select select) {
		SelectBody body = select.getSelectBody();
		if (body instanceof PlainSelect) {
			PlainSelect plainSelect = (PlainSelect) body;
			Limit limit = plainSelect.getLimit();
			if (limit != null) {
				threadLocal.set(limit);
				return true;
			}
		}
		return false;
	}

	public PageData buildPageData(Object[] values,ParameterEntry entry) {
		Limit limit=threadLocal.get();
		if (limit != null) {
			PageData pageData=new PageData();
			Integer limitTemp = entry.getPositionMap().get("limit");
			int limitIndex=0;
			Long limitValue;
			if (limitTemp == null) {
				limitValue = limit.getRowCount();
			} else {
				limitIndex = limitTemp;
				limitValue = Long
						.valueOf(
								String.valueOf(values[limitTemp
										.intValue() - 1])).longValue();
			}
			pageData.setLimitIndex(limitIndex);
			pageData.setLimitValue(limitValue);
			int startIndex=0;
			Long startValue;
			Integer startTemp = entry.getPositionMap().get("start");
			if (startTemp == null) {
				startValue = limit.getOffset();
			} else {
				startIndex = startTemp;
				startValue = Long
						.valueOf(
								String.valueOf(values[startTemp
										.intValue() - 1])).longValue();
			}
			pageData.setStartIndex(startIndex);
			pageData.setStartValue(startValue);
			return pageData;
		}
		return null;
	}

}
